package shop.core.common.oscache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import shop.services.manage.systemSetting.SystemSettingService;
import shop.services.manage.systemSetting.bean.SystemSetting;
import shop.services.manage.task.TaskService;
import shop.services.manage.task.bean.Task;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 缓存管理器。 后台项目可以通过接口程序通知该类重新加载部分或全部的缓存
 *
 * @author huangf
 */
public class ManageCache {
    private static final Logger logger = LoggerFactory.getLogger(ManageCache.class);

    /**
     * manage后台
     */
    @Resource(name = "taskServiceManage")
    private TaskService taskService;
    @Autowired
    private SystemSettingService systemSettingService;
    @Autowired
    private SystemManager systemManager;
    @Value(value = "classpath:area.json")
    private org.springframework.core.io.Resource data;


    /**
     * 加载全部的缓存数据
     *
     * @throws Exception
     */
    public void loadAllCache() throws Exception {
        logger.error("ManageCache.loadAllCache...");
        loadSystemSetting();
        loadTask();
        loadAreaData();
        logger.error("后台缓存加载完毕!");
    }

    /**
     * 加载地理区域数据
     */
    public void loadAreaData() {
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            File file = data.getFile();
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {
            logger.error(""+e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        systemManager.setAreaData(buffer.toString());
    }

    /**
     * 加载系统配置信息
     */
    public void loadSystemSetting() {
        SystemSetting systemSetting = systemSettingService.selectOne(new SystemSetting());
        if (systemSetting == null) {
            throw new NullPointerException("未设置本地环境变量，请管理员在后台进行设置");
        }
        systemManager.setSystemSetting(systemSetting);
    }

    /**
     * 加载定时任务
     */
    public void loadTask() {
        List<Task> list = taskService.selectList(null);
        for (Task task : list) {
            try {
                taskService.addTask(task);
            } catch (Exception e) {
                logger.error("加载定时任务异常" + e);
            }

        }

    }
}
